import axios, { AxiosRequestConfig, Method } from "axios";
/*设置baseURL*/
let baseURL = "/api";
// process.env.NODE_ENV  用于判断当前运行环境，根据 npm run serve 或 npm run build
if (process.env.NODE_ENV === "production") {
  // 最终部署地址
  baseURL = "/api";
}
axios.defaults.timeout = 30000;
axios.defaults.baseURL = baseURL;
axios.interceptors.request.use(
  (config) => {
    // 在发送请求之前做些什么
    // console.log('process.env.srconfig',process.env.srconfig)
    if (localStorage.getItem("token")) {
      // config.headers.token = localStorage.getItem("token");
      if(config.headers){
        let token = localStorage.getItem("token") + "";
        console.log("token: ",token);
        
        config.headers["Authorization"] = token;
      }
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
const action = (url: string, data: any, method: Method) => {
  return new Promise((resolve, reject) => {
    let params: AxiosRequestConfig = {
      method: method,
      url: url,
      withCredentials: true,
    };
    if (method == "GET") {
      params.params = data;
    } else {
      params.data = data;
    }
    axios(params)
      .then((response) => {
        resolve(response.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
};
const get = async (url: string, data: any): Promise<any> => {
  return action(url, data, "GET");
};
const post = async (url: string, data: any): Promise<any> => {
  return action(url, data, "POST");
};
const del = async (url: string, data: any): Promise<any> => {
  return action(url, data, "DELETE");
};
const put = async (url: string, data: any): Promise<any> => {
  return action(url, data, "PUT");
};
export default {
  get,
  post,
  del,
  put,
};
